package com.ff.kvm.service.impl;

import com.ff.kvm.common.eunm.StatusEnum;
import com.ff.kvm.common.third_util.AliyunOSSUtil;
import com.ff.kvm.common.third_util.TencentOSSUtil;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.service.UtilService;
import com.qcloud.cos.exception.CosClientException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class UtilServiceImpl implements UtilService {
    @Override
    public Response<String> upload(HttpServletRequest request) {
        Response<String> response = new Response<>();
        InputStream inputStream = null;
        try {

            Part file = request.getPart("file");
            if (file != null) {
                inputStream = file.getInputStream();

                Response<String> localResponse2 = upload(inputStream, file.getSubmittedFileName());
                return localResponse2;
            }
            response.setCode(StatusEnum.VD_EMPTY_UP_FILE.code());
            response.setMsg(StatusEnum.VD_EMPTY_UP_FILE.description());
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(StatusEnum.VD_ERROR_UP_FILE.code());
            response.setMsg(StatusEnum.VD_ERROR_UP_FILE.description());
            return response;
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Response<String> upload(InputStream inputStream, String name) {
        Response<String> response = new Response<>();
        String path;
        try{
            path = AliyunOSSUtil.upload((FileInputStream)inputStream, name);
        } catch (CosClientException e) {
            response.setCode(StatusEnum.DATA_ERROR.code());
            response.setMsg(e.getMessage());
            return response;
        } catch (Exception e) {
            response.setCode(StatusEnum.DATA_ERROR.code());
            response.setMsg(e.getMessage());
            return response;
        }
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        response.setData(path);
        return response;
    }
}
